package operation;

import entity.text.PaperEntity;

import java.io.File;
import java.io.FileReader;
import java.util.ArrayList;

/**
 * @author ：hzs
 * @date ：Created in 2020/12/10 16:44
 * @description：
 * @modified By：
 * @version: $
 */
public class TxtAbstractFileOperation extends AbstractFileOperation {
    @Override
    public String loadTextFromFile(File file) {
        String result = null;
        try {
            FileReader fileReader = new FileReader(file);
            int ch = 0;
            StringBuffer stringBuffer = new StringBuffer();
            while ((ch = fileReader.read()) != -1) {
                if (((char) ch) != '\r') {
                    stringBuffer.append((char) ch);
                }
            }
            result = stringBuffer.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    @Override
    public PaperEntity getPaperEntityFromFile(File file) throws Exception {
        String fileName = file.getName();
        if (!fileName.endsWith(".txt") && !fileName.endsWith(".TXT")) {
            throw new Exception("文件类型错误，不是txt文件");
        }
        String fullText = loadTextFromFile(file);
        String fileNameCode = getFileNameCode(file);
        PaperEntity paperInformationFromFile = citationDAO.getPaperInformationFromFile(fileNameCode);
        if (paperInformationFromFile == null) {
            System.out.println("加载文件信息失败：" + fileName);
            paperInformationFromFile = new PaperEntity();
        }
        this.spliter = new ArrayList<>();
        fullText = fullText.replace("\n?", "\n");
        this.paperText = removeHeaderAndFooter(fullText);
        paperInformationFromFile.setPaperText(this.paperText);
        double lineLength = countWordOneLine(file);
        paperInformationFromFile.setLineLength(lineLength);
        preSplit();
        doSplit();
        afterSplit(paperInformationFromFile);
        return paperInformationFromFile;
    }

}
